<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class Media extends CI_Model {

    private $CI;
    
    function __construct() {
        parent::__construct();
    }
    
	public function get($object_id,$row_id) {
		return $this
			->db
			->where('object_id',$object_id)
			->where('row_id',$row_id)
			->join('user','user.id=media.uploaded_by','left')
			->select('media.*, user.id AS user_id, user.email AS user_email')
			->get('media')
			->result();

	}
	
	public function add($object_id,$row_id,$data) {
		$columns = array(
			'uploaded_by'=>$this->user->get_current()->id,
			'filename'=>$data['file_name'],
			'object_id'=>$object_id,
			'row_id'=>$row_id
		);

		$this->load->model('language');
		foreach ($this->language->get_all() as $language) {
			$this->db->query("ALTER TABLE media ADD caption_$language->id TEXT");
			$columns["caption_$language->id"] = $data['client_name'];
		}
		
		$this
			->db
			->insert('media',$columns);
			
		return $this->db->insert_id();
	}
	
	public function delete($media_id) {
		$filename = $this
			->db
			->where('id',$media_id)
			->get('media')
			->row()
			->filename;

		if ($this->db->_error_number()!=0)
			throw new Exception("Media #$media_id not found in database: ".$this->db->_error_message());
		
		$this
			->db
			->where('id',$media_id)
			->delete('media');
			
		if (!unlink(URBAN_UPLOAD_PATH.$filename))
			throw new Exception("File '$filename' for media #$media_id could not be deleted from filesystem");
	}
	
	public function update_captions($media_id,$captions) {
		$affected_rows = 0;
		
		$this->load->model('language');
		foreach ($captions as $caption_id=>$caption)
    		$this->db->query("ALTER TABLE media ADD $caption_id TEXT");

    	$this->db->where('id',$media_id)->update('media',$captions);

		if ($this->db->_error_number()!=0)
			throw new Exception("Could not set captions for #$media_id".$this->db->_error_message());

    	if ($this->db->affected_rows() == 0)
			throw new Exception("Could not find #$media_id");
		
	} 
    
}